package BaseService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

func Update(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	// 修改时间
	data["update_at"] = time.Now().Unix()
	// 增加附加数据
	if req.UpdateInsertData != nil {
		otherData := req.UpdateInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 删除更新时不需要的字段
	DelIgnoreProperty(data, req.UpdateIgnoreProperty)
	// 编辑前方法
	if req.UpdateBeforeFn != nil {
		respRes := req.UpdateBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}

	// 过滤不正确的参数
	data, err := toolsDb.FilterColumnParams(g.DB(), false, data, req.TableName)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where("id", req.Id).Update(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	row, err := res.RowsAffected()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if row > 0 {
		if req.UpdateAfterFn != nil {
			respRes := req.UpdateAfterFn(r, data, g.Map{
				"id": data["id"],
			})
			if respRes.Code != 0 {
				return respRes
			}
		}
		// 尝试删除缓存
		if g.Cfg().GetBool("site.BaseCacheIsOpen") {
			tools.ClaerCacheByKeyPrefix("backCache:" + req.TableName + ":*")
		}

		return response.SuccessByRequestMessage(nil, "编辑成功")
	} else {
		return response.FailByRequestMessage(nil, "编辑失败")
	}
}
